import { h, resolveComponent, computed, renderSlot } from 'vue'

// 定义类型接口
interface Column {
  prop?: string
  label?: string
  width?: number
  type?: string
  render?: (value: any, row: any) => any
  items?: Array<{
    key: string
    text: string
    click: (row: any) => void
  }>
  [key: string]: any
}

interface TableStore {
  columns: Column[]
  data: any[]
  colWidths: number[]
  contentWidth: number
}

interface Props {
  store: TableStore
}

// 表格单元格基础样式
const cellBaseClass = [
  'cg-table__cell',
  'hover:bg-accent',
  'border-solid',
  'border-t-0',
  'border-l-0',
  'border-r-0',
  'border-b-1',
  'border-gray-100'
]

// 操作列单元格样式
const operationCellClass = [...cellBaseClass, 'operation-cell']

// 使用setup函数组件方式
const TableBody = {
  name: 'CGTableBody',
  props: {
    store: {
      type: Object,
      required: true
    }
  },
  setup(props: Props, { slots }: any) {
    // 计算表格宽度
    const tableWidth = computed(() => {
      return props.store?.contentWidth || '100%'
    })

    // 渲染操作按钮
    const renderOperationButtons = (column: Column, row: any) => {
      const CGButton = resolveComponent('cg-button')
      const buttons: Array<any> = []

      if (Array.isArray(column.items)) {
        column.items.forEach((item) => {
          buttons.push(
            h(
              CGButton,
              {
                size: 'sm',
                onClick: () => item.click(row),
                key: item.key,
                type: 'text',
                color: '#32aafe'
              },
              { default: () => item.text }
            )
          )
        })
      }

      return buttons
    }

    // 渲染数据单元格
    const renderDataCell = (column: Column, row: any) => {
      let data = ''

      // 如果有prop，则从数据行中获取对应的值
      if (column.prop && row) {
        data = row[column.prop]
      }

      // 如果有render函数，则使用render函数处理数据
      if (typeof column.render === 'function') {
        const renderedData = column.render(data, row)
        return renderedData
      }

      return data
    }

    // 渲染表格行
    const renderTableRow = (row: any, index: number) => {
      const { columns } = props.store

      return h(
        'tr',
        {
          key: row?.id || row?.key || index,
          class: ['hover:bg-gray-50']
        },
        columns.map((column: Column) => {
          // 处理操作列
          if (column.type === 'operation') {
            return h(
              'td',
              {
                class: operationCellClass
              },
              [
                h('div', { class: ['cell', 'whitespace-nowrap'] },
                  renderOperationButtons(column, row)
                )
              ]
            )
          }

          // 处理普通列
          return h(
            'td',
            {
              class: cellBaseClass
            },
            [
              h('div', { class: 'cell' },
                renderDataCell(column, row)
              )
            ]
          )
        })
      )
    }

    // 渲染列宽定义
    const renderColGroup = () => {
      const { columns, colWidths } = props.store

      if (!columns || !columns.length || !colWidths) {
        return null
      }

      return h(
        'colgroup',
        {},
        columns.map((column: Column, index: number) => {
          const propName = column.prop || column.type || `col-${index}`
          const width = colWidths[index] || 0

          return h(
            'col',
            {
              name: propName,
              key: propName,
              width: Math.max(0, width)
            }
          )
        })
      )
    }

    // 渲染空数据提示
    const renderEmptyData = () => {
      return h(
        'div',
        {
          class: 'cg-table__empty-block'
        },
        h(
          'div',
          {
            class: 'cg-table__empty-text'
          },
          '暂无数据'
        )
      )
    }

    return () => {
      if (!props.store) {
        return null
      }

      const { columns, data } = props.store
      const hasData = data && Array.isArray(data) && data.length > 0
      const hasColumns = columns && Array.isArray(columns) && columns.length > 0

      // 检查是否有必要渲染表格
      if (!hasColumns) {
        return null
      }

      return h(
        'table',
        {
          class: 'cg-table__body',
          cellspacing: 0,
          cellpadding: 0,
          border: 0,
          style: {
            width: typeof tableWidth.value === 'number' ? `${tableWidth.value}px` : tableWidth.value
          }
        },
        [
          // 渲染列宽定义
          hasData ? renderColGroup() : null,

          // 渲染表格内容
          h(
            'tbody',
            {},
            hasData
              ? data.map(renderTableRow)
              : renderEmptyData()
          ),

          // 渲染插槽内容
          slots.default ? renderSlot(slots, 'default') : null
        ]
      )
    }
  }
}

export default TableBody
